/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, { ModalForm, ProFormTextArea } from '@ant-design/pro-form';
import { Button, Tooltip, message, Space, Popconfirm } from 'antd';
import { connect, useSelector } from 'umi';
import { getWsPartnerList, changeWsPartnerStatus } from '@/services/operatorManagement';
import KbImage from '@/components/KbImage';
import { debounce } from 'lodash';
import type { Dispatch } from 'umi';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import type { TableColumns, Platform } from './types/WsPartner';

interface WsPartnerProps {
  dispatch: Dispatch;
  platforms: Platform;
}

interface RefuseModalProps {
  id: string;
  children: JSX.Element;
  tableRef: ActionType | undefined;
}

const RefuseModal: React.FC<RefuseModalProps> = ({ id, children, tableRef }) => {
  return (
    <ModalForm
      title='请填写拒绝原因'
      trigger={children}
      width={600}
      modalProps={{ centered: true }}
      onFinish={async (values) => {
        const { code, msg } = await changeWsPartnerStatus({ id, status: 2, reason: values.text });
        if (code == 0) {
          message.success(msg);
          tableRef?.reload();
          return true;
        }
        message.error(msg);
        return false;
      }}
    >
      <ProForm.Group>
        <ProFormTextArea
          width='xl'
          name='text'
          placeholder='请输入原因'
          rules={[{ required: true, message: '请填写拒绝原因' }]}
          allowClear
        />
      </ProForm.Group>
    </ModalForm>
  );
};

const WsPartner: React.FC<WsPartnerProps> = ({ platforms, dispatch }) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();

  useEffect(() => {
    dispatch({
      type: 'wsPartner/getPlatForm',
    });
  }, []);

  const handleRequest = useCallback((params) => {
    const { current: page, pageSize, ...rest } = params;
    return getWsPartnerList({
      third_order_id: rest.third_order_id,
      third_mark: rest.third_mark === 'all' ? undefined : rest.third_mark,
      status: rest.status === 'all' ? undefined : rest.status,
      page,
      page_size: pageSize,
    });
  }, []);

  const onPay = useCallback(
    debounce(
      async (id) => {
        const { code, msg } = await changeWsPartnerStatus({ id, status: 1 });
        if (code == 0) {
          message.success(msg);
          actionRef.current?.reload();
        } else {
          message.error(msg);
        }
      },
      300,
      {
        leading: true,
        trailing: false,
      },
    ),
    [],
  );

  const columns: ProColumns<TableColumns>[] = [
    {
      title: '序号',
      dataIndex: 'num',
      search: false,
      width: 80,
      align: 'center',
    },
    {
      title: '电商平台订单号',
      dataIndex: 'third_order_id',
      align: 'center',
    },
    {
      title: '电商平台',
      dataIndex: 'third_mark',
      align: 'center',
      initialValue: 'all',
      valueEnum: platforms,
    },
    {
      title: '订单总价',
      dataIndex: 'price',
      search: false,
      align: 'center',
    },
    {
      title: '扣手续费后价格',
      dataIndex: 'settlement_amount',
      search: false,
      align: 'center',
    },
    {
      title: '商家名称',
      dataIndex: 'third_name',
      search: false,
      align: 'center',
    },
    {
      title: '上传图片',
      dataIndex: 'img',
      search: false,
      render: (text) => {
        return <KbImage width={30} height={30} src={`${text}`} />;
      },
      align: 'center',
    },
    {
      title: '快递员姓名',
      dataIndex: 'realname',
      search: false,
      align: 'center',
    },
    {
      title: '快递员账号',
      dataIndex: 'mobile',
      search: false,
      align: 'center',
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      initialValue: 'all',
      valueEnum: {
        all: {
          text: '全部',
        },
        '0': {
          text: '未处理',
        },
        '1': {
          text: '已打款',
        },
        '2': {
          text: '已拒绝',
        },
      },
      render: (_, record) => {
        let status = '';
        switch (record.status) {
          case '0':
            status = '未处理';
            break;
          case '1':
            status = '已打款';
            break;
          case '2':
            status = '已拒绝';
            break;
          default:
            status = '-';
            break;
        }
        let node: JSX.Element = <a key='a' />;
        if (record.status === '2') {
          node = (
            <Tooltip key='check' title={record.reason} trigger='click'>
              <a style={{ marginLeft: 10 }}>查看</a>
            </Tooltip>
          );
        }
        return [status, node];
      },
      align: 'center',
    },
    {
      title: '申请时间',
      dataIndex: 'create_time',
      search: false,
      align: 'center',
    },
    {
      title: '处理时间',
      dataIndex: 'audit_time',
      search: false,
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'option',
      fixed: 'right',
      width: winSize === 'xs' ? 80 : 120,
      render: (_, record) => (
        <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
          {record.status === '0'
            ? [
                <Popconfirm title='确定打款？' onConfirm={() => onPay(record.id)}>
                  <Button type='primary' danger size='small'>
                    打款
                  </Button>
                </Popconfirm>,
                <RefuseModal key='refuse' id={record.id} tableRef={actionRef.current}>
                  <a>拒绝</a>
                </RefuseModal>,
              ]
            : null}
        </Space>
      ),
      align: 'center',
    },
  ];
  return (
    <PageContainer>
      <DragTable>
        <ProTable<TableColumns>
          className='kb-pro-table'
          actionRef={actionRef}
          rowKey='id'
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            defaultCollapsed: false,
          }}
          request={handleRequest}
          columns={columns}
          options={false}
          pagination={{
            pageSize: 15,
            showSizeChanger: false,
          }}
          scroll={{ x: 1600 }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default connect(({ wsPartner }: ConnectState) => ({
  platforms: wsPartner.platforms,
}))(React.memo(WsPartner));
